package cn.copera.kaka.utils;

import java.io.IOException;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import cn.copera.kaka.bean.Articles;
import cn.copera.kaka.bean.InMessage;
import cn.copera.kaka.bean.NewsOutMessage;
import cn.copera.kaka.bean.OutMessage;
import cn.copera.kaka.controller.CommonController;
import cn.copera.kaka.model.ExchangeRule;
import cn.copera.kaka.model.Order;
import cn.copera.kaka.model.Shop;
import cn.copera.kaka.model.ShopImage;
import cn.copera.kaka.model.Track;
import cn.copera.kaka.model.UserShop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.thoughtworks.xstream.XStream;

/**
 * 微信工具类
 */
public class WxUtils {
	// http客户端
	public static DefaultHttpClient httpclient;
	// 自定义 token
	public static String TOKEN = "kaka";
	// 使用的服务器IP地址
//	private static String IPADDRESS = "121.42.151.128";  //卡卡足迹
	private static String IPADDRESS = "dyywx.shijun.org/kakawx";  //新测试服114.215.153.239
//	private static String IPADDRESS = "429483.dowei8.com";//本地
	
	//开发者凭据
//	private static String APPID = "wxdb7d946a212d8ff3";//阿里云-科博瑞卡卡
//	private static String APPSECRET = "423ae91a2877392889070510c4a7aeda";//阿里云-科博瑞卡卡
	public static String APPID = "wx25d8154f7a1cd8a7";//卡卡足迹
	public static String APPSECRET = "c8184573e16c4716a78ed2349cd00270";//卡卡足迹
	public static String ENCODINGAESKEY = "eqgPaHIVEaVdeJuChKuUaLQbYWgtvsjAAa6j1EWrIR2";//卡卡足迹
	
	static {
		httpclient = new DefaultHttpClient();
		httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient); // 接受任何证书的浏览器客户端
	}

	public static void main(String[] args) {
		try {
			// 获取accessToken -参数appid，secret
			String accessToken = getAccessToken(APPID, APPSECRET);
			System.out.println(accessToken);
//			String s = "ole6Gt61n_uHyUoB7w3sFgHUQSqs";
//			String res = getWxUserInfo1(s, accessToken);
//			System.out.println(res);			
//			String menu = "{\"button\":[  {\"type\":\"click\", \"name\":\"我的二维码\",  \"key\":\"CODE\"},{ \"type\":\"click\", \"name\":\"我的足迹\", \"key\":\"TRACK\"},{ \"type\":\"view\", \"name\":\"我是店长\", \"url\":\"http://"+IPADDRESS+"/regrist\"}] }";

//			String res = createMenu(menu, accessToken);
//			System.out.println(res);
/*			String s = "{\"button\":[{\"name\":\"公共服务\",\"sub_button\":[{\"type\":\"click\",\"name\":\"查询服务\",\"key\":\"m_searchServer\"},{\"type\":\"click\",\"name\":\"电费缴查\",\"key\":\"m_price\"},{\"type\":\"click\",\"name\":\"营业网点\",\"key\":\"m_branch\"}]},"
					+"{\"name\":\"专业服务\",\"sub_button\":[{\"type\":\"click\",\"name\":\"专业系统\",\"key\":\"m_proSystem\"},{\"type\":\"click\",\"name\":\"电力期刊\",\"key\":\"m_magazine\"},{\"type\":\"click\",\"name\":\"我院业务\",\"key\":\"m_intro\"},{\"type\":\"click\",\"name\":\"页面调试\",\"key\":\"m_test\"}]},"
					+"{\"name\":\"互动服务\",\"sub_button\":[{\"type\":\"click\",\"name\":\"故障&咨询\",\"key\":\"m_quiz\"},{\"type\":\"click\",\"name\":\"导航我院\",\"key\":\"m_guide\"},{\"type\":\"view\",\"name\":\"用电常识\",\"url\":\"http://"+IPADDRESS+"/wx4dyy/kownledge/list\"},{\"type\":\"click\",\"name\":\"微电力展\",\"key\":\"m_recom\"},{\"type\":\"click\",\"name\":\"志愿者服务队\",\"key\":\"m_volunteer\"}]}]}";
*/
			//保留操作说明菜单
			/*String s = "{\"button\":[{\"name\":\"公共服务\",\"sub_button\":[{\"type\":\"click\",\"name\":\"查询服务\",\"key\":\"m_searchServer\"},{\"type\":\"click\",\"name\":\"电费缴查\",\"key\":\"m_price\"},{\"type\":\"view\",\"name\":\"安全用电\",\"url\":\"http://"+IPADDRESS+"/wx4dyy/kownledge/list\"}]},"
					+"{\"name\":\"专业服务\",\"sub_button\":[{\"type\":\"click\",\"name\":\"专业系统\",\"key\":\"m_proSystem\"},{\"type\":\"click\",\"name\":\"电力期刊\",\"key\":\"m_magazine\"},{\"type\":\"click\",\"name\":\"我院业务\",\"key\":\"m_intro\"}]},"
					+"{\"name\":\"互动服务\",\"sub_button\":[{\"type\":\"click\",\"name\":\"故障&咨询\",\"key\":\"m_quiz\"},{\"type\":\"click\",\"name\":\"导航我院\",\"key\":\"m_guide\"},{\"type\":\"view\",\"name\":\"操作说明\",\"url\":\"http://mp.weixin.qq.com/s?__biz=MjM5MDA0NjY1MA==&mid=10014419&idx=1&sn=e892940d93cba1fee6f2967bb4dc5945#rd\"}]}]}";*/
/*			String res = createMenu(s, accessToken);*/
			
			// 获取用户昵称
			//String s = "oujd1jo8gBE8BOEMKSLIjyOqA5VI";
			//String res = getWxUserInfo(s, accessToken);
			//System.out.println(res);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getJsapi_ticket(String access_token) throws Exception {
		HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi");
		HttpResponse response = httpclient.execute(get);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		JSONObject object = JSON.parseObject(jsonStr);
		return object.getString("ticket");
	}

	/**
	 * 创建菜单
	 */
	public static String createMenu(String params, String accessToken) throws Exception {
		HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken);
		httpost.setEntity(new StringEntity(params, "UTF-8"));
		HttpResponse response = httpclient.execute(httpost);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		System.out.println(jsonStr);
		JSONObject object = JSON.parseObject(jsonStr);
		return object.getString("errmsg");
	}
	private static void setMsgInfo(OutMessage oms,InMessage msg) throws Exception {
		// 设置发送信息
		Class<?> outMsg = oms.getClass().getSuperclass();
		Field CreateTime = outMsg.getDeclaredField("CreateTime");
		Field ToUserName = outMsg.getDeclaredField("ToUserName");
		Field FromUserName = outMsg.getDeclaredField("FromUserName");

		ToUserName.setAccessible(true);
		CreateTime.setAccessible(true);
		FromUserName.setAccessible(true);

		CreateTime.set(oms, new Date().getTime());
		ToUserName.set(oms, msg.getFromUserName().replace("-", "a"));
		FromUserName.set(oms, msg.getToUserName());
	}
	
	/**
	 * 生成被关注时的内容xml字符串
	 * @param msg 接收来自微信的信息
	 * @return
	 */
	public static String getWelcomeContent(InMessage msg,String filename) {
		//认证处理（扫一扫）
//		String openid=msg.getFromUserName();
//		String urlname = URLEncoder.encode(openid);
//		String PICURL = URLEncoder.encode("http://"+IPADDRESS+"/images/"+filename);
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		String time = sdf.format(new Date());
//		String str = "n="+urlname+"&u="+openid+"&t="+time;
//		String encrypt = toHexString(str);
//		Date date = new Date();
//		String timestamp = Long.toString(date.getTime());
//		String str_dst = encrypt+"~"+timestamp+"~"+PICURL+"~"+"gh_a6c715cfac0f";
//		String picurl = "http://2.2.2.1/wx.jpg?href="+str_dst;
		
		//返回图文
		NewsOutMessage oms = new NewsOutMessage();
		try {
			setMsgInfo(oms,msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		XStream xs = XStreamFactory.init(true);
		String xml = "";
		List<Articles> arts = new ArrayList<Articles>();
		Articles artBig = new Articles(); //大图片
		artBig.setTitle("请出示给店铺扫描，获取卡点。");//标题
		//原来二维码返回图片地址"http://"+IPADDRESS+"/images/"+filename
		artBig.setPicUrl("http://"+IPADDRESS+"/images/"+filename); //360*200
		artBig.setDescription("点击此处可放大。");
		artBig.setUrl("http://"+IPADDRESS+"/code/"+msg.getFromUserName().replace("-", "a"));
		arts.add(artBig);
		((NewsOutMessage) oms).setArticles(arts);
		xs.alias("xml", oms.getClass());
		xs.alias("item", Articles.class);
		xml = xs.toXML(oms);
		return xml;
	}
	
	/**
	 * 获取accessToken
	 */
	public static String getAccessToken(String appid, String secret) throws Exception {
		HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
		HttpResponse response = httpclient.execute(get);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		JSONObject object = JSON.parseObject(jsonStr);
		return object.getString("access_token");
	}
	
	/**
	 * 查询菜单
	 */
	public static String getMenuInfo(String accessToken) throws Exception {
		HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + accessToken);
		HttpResponse response = httpclient.execute(get);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		return jsonStr;
	}
	
	/**
	 * 删除自定义菜单
	 */
	public static String getAccessToken(String accessToken) throws Exception {
		HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + accessToken);
		HttpResponse response = httpclient.execute(get);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		JSONObject object = JSON.parseObject(jsonStr);
		return object.getString("errmsg");
	}
	
	/**
	 * 获取用户基本信息
	 * 其中nickname为昵称
	 */
	public static String getWxUserInfo(String openid, String accessToken) throws Exception {
		HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken+"&openid="+openid+"&lang=zh_CN");
		HttpResponse response = httpclient.execute(httpost);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		System.out.println(jsonStr);
		JSONObject object = JSON.parseObject(jsonStr);
		return object.getString("nickname");
	}
	/**
	 * 获取用户基本信息
	 * 其中headimgurl为用户头像
	 */
	public static String getWxUserInfoPic(String openid, String accessToken) throws Exception {
		HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken+"&openid="+openid+"&lang=zh_CN");
		HttpResponse response = httpclient.execute(httpost);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		System.out.println(jsonStr);
		JSONObject object = JSON.parseObject(jsonStr);
		return object.getString("headimgurl");
	}
	/**
	 * 获取用户基本信息
	 * 其中nickname为昵称
	 */
	public static String getWxUserInfo1(String openid, String accessToken) throws Exception {
		HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken+"&openid="+openid+"&lang=zh_CN");
		HttpResponse response = httpclient.execute(httpost);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		System.out.println(jsonStr);
		JSONObject object = JSON.parseObject(jsonStr);
		return object.getString("headimgurl");
	}
	
	/**
	 * 获取用户图片信息
	 * 其中filename为文件名
	 */
	public static String getWxPicInfo(String url) throws Exception {
		HttpGet get = HttpClientConnectionManager.getGetMethod(url);
		HttpResponse response = httpclient.execute(get);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		JSONObject object = JSON.parseObject(jsonStr);
		return object.getString("filename");		
	}
	/**
	 * 访问校验
	 */
	public static boolean checkSignature(String signature,String timestamp,String nonce){
		try {
			String[] str = { TOKEN, timestamp, nonce };
			Arrays.sort(str); // 字典序排序
			String bigStr = str[0] + str[1] + str[2];
			// SHA1加密
			String digest = new SHA1().getDigestOfString(bigStr.getBytes()).toLowerCase();
			// 确认请求来至微信
			if (digest.equals(signature)) {
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}
	
	/**
	 * 将输入流转为字符串
	 */
	public static final String inputStream2String(InputStream in) throws UnsupportedEncodingException, IOException{
		if(in == null)
			return "";
		
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n, "UTF-8"));
		}
		return out.toString();
	}
	
	/**
	 * 点击我的二维码的内容xml字符串
	 * @param msg 接收来自微信的信息
	 * @return
	 */
	public static String getTwoCode(InMessage msg,String filename) {
		NewsOutMessage oms = new NewsOutMessage();
		try {
			setMsgInfo(oms,msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		XStream xs = XStreamFactory.init(true);
		String xml = "";
		List<Articles> arts = new ArrayList<Articles>();
		Articles artBig = new Articles(); //大图片
		artBig.setTitle("请出示给店铺扫描，获取卡点。");//标题
		artBig.setPicUrl("http://"+IPADDRESS+"/images/"+filename); //360*200
		artBig.setDescription("点击此处可放大。");
		artBig.setUrl("http://"+IPADDRESS+"/code/"+msg.getFromUserName().replace("-", "a"));
		arts.add(artBig);
		((NewsOutMessage) oms).setArticles(arts);
		xs.alias("xml", oms.getClass());
		xs.alias("item", Articles.class);
		xml = xs.toXML(oms);
		return xml;
	}

	/**
	 * 点击我的足迹的内容xml字符串
	 * @param msg 接收来自微信的信息
	 * @return
	 */
	public static String getFoot(InMessage msg) {
		NewsOutMessage oms = new NewsOutMessage();
		try {
			setMsgInfo(oms,msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		XStream xs = XStreamFactory.init(true);
		String xml = "";
		List<Articles> arts = new ArrayList<Articles>();
		Articles artBig = new Articles(); //大图片
		artBig.setTitle("您的足迹");//标题
		artBig.setPicUrl("http://"+IPADDRESS+"/images/album-hc.jpg"); //360*200
		artBig.setDescription("点击进入店铺列表。");
		artBig.setUrl("http://"+IPADDRESS+"/shopList/"+msg.getFromUserName().replace("-", "a"));
		arts.add(artBig);
		((NewsOutMessage) oms).setArticles(arts);
		xs.alias("xml", oms.getClass());
		xs.alias("item", Articles.class);
		xml = xs.toXML(oms);
		return xml;
	}
	/**
	 * 扫描弹出店面导向页面
	 * @param msg
	 * @param shopName
	 * @param shopId
	 * @param shopImage
	 * @return
	 */
	public static String getShopScanContent(InMessage msg,String shopName,String shopId,String shopImage) {
		String openid = msg.getFromUserName();
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",openid,shopId);
		if(us==null){
			UserShop us1 = new UserShop();
			us1.set("id", System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).set("del_flag", "0").set("use_point",BigDecimal.valueOf(0)).set("count_point", BigDecimal.valueOf(0)).set("check_time", new Date()).set("check_time1", new Date()).save();	
			Order o = new Order();
			ExchangeRule rule = ExchangeRule.dao.findFirst("select * from ka_exchange_rule where shop_id=? ORDER BY create_date desc LIMIT 0,1",shopId);
			if(rule!=null){
			o.set("id",  System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).set("time", rule.getTimestamp("create_date")).save();
			}else{
				o.set("id",  System.currentTimeMillis() + "").set("openid", openid).set("shop_id", shopId).save();	
			}			
		}
		int kadian=1;
		Order order = Order.dao.findFirst("select * from ka_order where openid=? and shop_id=?",msg.getFromUserName(),shopId);
		String qiandao = "no";
		UserShop us2 = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",openid,shopId);
		if(us2 !=null){
		if(us2.getTimestamp("qiandao_time")!=null){
		  SimpleDateFormat format1 = new SimpleDateFormat("d"); 
		  Date d = new Date();
		  String date = format1.format(d);		
		  String date1 = format1.format(us2.getTimestamp("qiandao_time"));	
		  if(!date.equals(date1)){
				us2.set("qiandao_time", new Date()).update();
				Date date2 = new Date();
		        Calendar cal = Calendar.getInstance();
		        cal.setTime(date2);
		        Shop shop = Shop.dao.findById(shopId);
		        cal.add(Calendar.MONTH, Integer.parseInt(shop.getStr("valid_date")));
				Track track = new Track();
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
				track.set("id", System.currentTimeMillis() + "").set("nick_name", openid).set("create_date", new Date()).set("del_flag", "0").set("update_date", new Date()).set("create_date_str", format.format(new Date())).set("state", "0").set("count", kadian).set("usable_count", kadian).set("shop_id", shopId).set("valid_date", cal.getTime()).set("remarks", "签到，获取"+kadian+"个卡点").set("create_name", "我自己").save();
				if(order !=null){
				order.set("time", new Date()).update();
				}
				qiandao="yes";
		  }				
	}else{
		us2.set("qiandao_time", new Date()).update();
		Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        Shop shop = Shop.dao.findById(shopId);
        cal.add(Calendar.MONTH, Integer.parseInt(shop.getStr("valid_date")));
		Track track = new Track();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		track.set("id", System.currentTimeMillis() + "").set("nick_name", openid).set("create_date", new Date()).set("del_flag", "0").set("update_date", new Date()).set("create_date_str", format.format(new Date())).set("state", "0").set("count", kadian).set("usable_count", kadian).set("shop_id", shopId).set("valid_date", cal.getTime()).set("remarks", "关注，获取"+kadian+"个卡点").set("create_name", "我自己").save();
		if(order !=null){
			order.set("time", new Date()).update();
		}
		qiandao="yes";
	}
		}
		
		NewsOutMessage oms = new NewsOutMessage();
		try {
			setMsgInfo(oms,msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		XStream xs = XStreamFactory.init(true);
		String xml = "";
		
		List<Articles> arts = new ArrayList<Articles>();
		Articles artBig = new Articles(); //大图片
		artBig.setTitle(shopName);//标题
		if(shopImage==null){
			artBig.setPicUrl("http://"+IPADDRESS+"/images/logo_kaka.png");
		}else{
		artBig.setPicUrl(shopImage); //360*200
		}
		if(qiandao.equals("no")){
		artBig.setDescription("点击此处可进入店铺首页。\n（今天已获得卡点）");
		}else{
		artBig.setDescription("点击此处可进入店铺首页。\n（签到成功，获得卡点）");	
		}
		artBig.setUrl("http://"+IPADDRESS+"/shopIndex/"+shopId+"-"+msg.getFromUserName().replace("-", "a"));
		arts.add(artBig);
		System.out.println(IPADDRESS);
 	 ((NewsOutMessage) oms).setArticles(arts);
		xs.alias("xml", oms.getClass());
		xs.alias("item", Articles.class);
		xml = xs.toXML(oms);
		return xml;
	}
	
	/**
	 * 点击足迹新动静的内容xml字符串
	 * @param msg 接收来自微信的信息
	 * @return
	 */
	public static String getNewFoot(InMessage msg) {
		String userOpenId = msg.getFromUserName();   //用户微信OpenId
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=?",userOpenId);
		Order order = Order.dao.findFirst("select * from ka_order where openid=?",userOpenId);
		String url = CommonController.getServer();
		NewsOutMessage oms = new NewsOutMessage();
		try {
			setMsgInfo(oms,msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		XStream xs = XStreamFactory.init(true);
		String xml = "";
		List<Articles> arts = new ArrayList<Articles>();
		if(us==null || order==null){
		Articles artBig = new Articles(); //大图片
		artBig.setTitle("您尚未关注店铺，请您先关注店铺");//标题
		artBig.setPicUrl("http://"+IPADDRESS+"/images/firstVisit.jpg"); //360*200
		artBig.setDescription("点击此处可进入使用介绍");
		artBig.setUrl("http://"+IPADDRESS+"/help.jsp");
		arts.add(artBig);			
		}else{
			/*Shop shops = Shop.dao.findFirst("select id,head_image,shop_name,(SELECT o.time from ka_order o where o.shop_id = s.id and o.openid = '"+userOpenId+"') as time from ka_shop s where parent_id is null ORDER BY time desc LIMIT 0,1");*/
/*			SELECT ka_shop.id,head_image,shop_name,time from ka_shop left join ka_order on ka_shop.id=ka_order.shop_id where ka_order.openid = '"+userOpenId+"' GROUP BY shop_name ORDER BY ka_order.time desc LIMIT 0,1*/
			Shop shops = Shop.dao.findFirst("SELECT s.id,s.head_image,s.shop_name,(SELECT o.time from ka_order o where o.shop_id = s.id and o.openid = '"+userOpenId+"') as time from ka_shop s where s.parent_id is null and s.id in(SELECT l.shop_id from ka_order l where l.openid = '"+userOpenId+"') ORDER BY time desc LIMIT 0,1");
			ShopImage si = new ShopImage();
			if(shops!=null){
			 si = ShopImage.dao.findFirst("select * from ka_shop_image where shop_id=? and flag=?",shops.getStr("id"),"shop_img");
			}
			Articles artBig = new Articles(); //大图片
			artBig.setTitle(shops.getStr("shop_name"));//标题
			if(si==null){
				artBig.setPicUrl("http://"+IPADDRESS+"/images/logo_kaka.png");
			}else{
				artBig.setPicUrl(url+si.getStr("file_name"));
			}
			artBig.setUrl("http://"+IPADDRESS+"/shopIndex/"+shops.getStr("id")+"-"+userOpenId);
			arts.add(artBig);			
			List<Shop> shops1 = Shop.dao.find("SELECT s.id,s.head_image,s.shop_name,(SELECT o.time from ka_order o where o.shop_id = s.id and o.openid = '"+userOpenId+"') as time from ka_shop s where s.parent_id is null and s.id in(SELECT l.shop_id from ka_order l where l.openid = '"+userOpenId+"') ORDER BY time desc LIMIT 1,3");
			if(shops1!=null){
			for(Shop s : shops1){
				if(s!=null){
				Articles art = new Articles();
				art.setTitle(s.getStr("shop_name"));
				if(s.getStr("head_image")==null){
					art.setPicUrl("http://"+IPADDRESS+"/images/logo_kaka.png");
				}else{
					art.setPicUrl(url+s.getStr("head_image"));
				}
				art.setUrl("http://"+IPADDRESS+"/shopIndex/"+s.getStr("id")+"-"+userOpenId);
				arts.add(art);
				}
			}
			}
			Articles art2 = new Articles();
			art2.setTitle("更  多");
			art2.setPicUrl("http://"+IPADDRESS+"/images/album-hc.jpg"); //200*200
			art2.setUrl("http://"+IPADDRESS+"/shopList/"+userOpenId);
			arts.add(art2);									
		}
		((NewsOutMessage) oms).setArticles(arts);
		xs.alias("xml", oms.getClass());
		xs.alias("item", Articles.class);
		xml = xs.toXML(oms);
		return xml;		
	}

	//所有店铺
	public static String getAllShop(InMessage msg) {
		String userOpenId = msg.getFromUserName();   //用户微信OpenId
		NewsOutMessage oms = new NewsOutMessage();
		try {
			setMsgInfo(oms,msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		XStream xs = XStreamFactory.init(true);
		String xml = "";
		List<Articles> arts = new ArrayList<Articles>();
		Articles art2 = new Articles();
		art2.setTitle("所有店铺");
		art2.setPicUrl("http://"+IPADDRESS+"/images/allshop.jpg"); //200*200
		art2.setDescription("点击此处可进入所有店铺列表");
		art2.setUrl("http://"+IPADDRESS+"/searchList/"+userOpenId);
		arts.add(art2);											
		((NewsOutMessage) oms).setArticles(arts);
		xs.alias("xml", oms.getClass());
		xs.alias("item", Articles.class);
		xml = xs.toXML(oms);
		return xml;		
	}
	
	public static String getSmartWord(InMessage msg,cn.copera.kaka.bean.TextOutMessage ims){
		String userOpenId = msg.getFromUserName();   //用户微信OpenId
		String content = msg.getContent();
		NewsOutMessage oms = new NewsOutMessage();
		try {
			setMsgInfo(oms,msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		XStream xs = XStreamFactory.init(true);
		String xml = "";
		Shop shop = Shop.dao.findFirst("select * from ka_shop where x_code=?",content);
		
		if(shop==null){
			((cn.copera.kaka.bean.TextOutMessage) ims).setContent("输入店铺代码有误，请核实后重新输入。");
			xs = XStreamFactory.init(true);
			xs.alias("xml", ims.getClass());
			xml = xs.toXML(ims);		
		}else{
		UserShop us = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",userOpenId,shop.getStr("id"));		
		System.out.println("1");
		if(us==null){
			System.out.println("2");
			UserShop us1 = new UserShop();
			us1.set("id", System.currentTimeMillis() + "").set("openid", userOpenId).set("shop_id", shop.getStr("id")).set("del_flag", "0").set("use_point",BigDecimal.valueOf(0)).set("count_point", BigDecimal.valueOf(0)).set("check_time", new Date()).set("check_time1", new Date()).save();	
			Order o = new Order();
			ExchangeRule rule = ExchangeRule.dao.findFirst("select * from ka_exchange_rule where shop_id=? ORDER BY create_date desc LIMIT 0,1",shop.getStr("id"));
			if(rule!=null){
			o.set("id",  System.currentTimeMillis() + "").set("openid", userOpenId).set("shop_id", shop.getStr("id")).set("time", rule.getTimestamp("create_date")).save();
			}else{
				o.set("id",  System.currentTimeMillis() + "").set("openid", userOpenId).set("shop_id", shop.getStr("id")).save();	
			}			
		}
		int kadian=1;
		Order order = Order.dao.findFirst("select * from ka_order where openid=? and shop_id=?",msg.getFromUserName(),shop.getStr("id"));
		String qiandao = "no";
		UserShop us2 = UserShop.dao.findFirst("select * from ka_user_shop where openid=? and shop_id=?",userOpenId,shop.getStr("id"));
		if(us2 !=null){
		if(us2.getTimestamp("qiandao_time")!=null){
		  System.out.println("3");
		  SimpleDateFormat format1 = new SimpleDateFormat("d"); 
		  Date d = new Date();
		  String date = format1.format(d);		
		  String date1 = format1.format(us2.getTimestamp("qiandao_time"));	
		  if(!date.equals(date1)){
				us2.set("qiandao_time", new Date()).update();
				Date date2 = new Date();
		        Calendar cal = Calendar.getInstance();
		        cal.setTime(date2);
		        cal.add(Calendar.MONTH, Integer.parseInt(shop.getStr("valid_date")));
				Track track = new Track();
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
				track.set("id", System.currentTimeMillis() + "").set("nick_name", userOpenId).set("create_date", new Date()).set("del_flag", "0").set("update_date", new Date()).set("create_date_str", format.format(new Date())).set("state", "0").set("count", kadian).set("usable_count", kadian).set("shop_id", shop.getStr("id")).set("valid_date", cal.getTime()).set("remarks", "签到，获取"+kadian+"个卡点").set("create_name", "我自己").save();
				if(order !=null){
				order.set("time", new Date()).update();
				}
				qiandao="yes";
		  }				
	}else{
		System.out.println("4");
		us2.set("qiandao_time", new Date()).update();
		Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, Integer.parseInt(shop.getStr("valid_date")));
		Track track = new Track();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		track.set("id", System.currentTimeMillis() + "").set("nick_name", userOpenId).set("create_date", new Date()).set("del_flag", "0").set("update_date", new Date()).set("create_date_str", format.format(new Date())).set("state", "0").set("count", kadian).set("usable_count", kadian).set("shop_id", shop.getStr("id")).set("valid_date", cal.getTime()).set("remarks", "关注，获取"+kadian+"个卡点").set("create_name", "我自己").save();
		if(order !=null){
			order.set("time", new Date()).update();
		}
		qiandao="yes";
	}
		}
		
		ShopImage si = ShopImage.dao.findFirst("select * from ka_shop_image where shop_id=? and flag=?",shop.getStr("id"),"shop_img");
		String shopImage =null;
		if(si!=null){
		shopImage = si.getStr("file_name");
		}
		
		List<Articles> arts = new ArrayList<Articles>();
		Articles artBig = new Articles(); //大图片
		artBig.setTitle(shop.getStr("shop_name"));//标题
		if(shop.getStr("shop_name")==null){
			artBig.setPicUrl("http://"+IPADDRESS+"/images/logo_kaka.png");
		}else{
		artBig.setPicUrl(shopImage); //360*200
		}
		if(qiandao.equals("no")){
		artBig.setDescription("点击此处可进入店铺首页。\n（今天已获得卡点）");
		}else{
		artBig.setDescription("点击此处可进入店铺首页。\n（签到成功，获得卡点 ）");	
		}
		artBig.setUrl("http://"+IPADDRESS+"/shopIndex/"+shop.getStr("id")+"-"+msg.getFromUserName().replace("-", "a"));
		arts.add(artBig);
 	 ((NewsOutMessage) oms).setArticles(arts);
		xs.alias("xml", oms.getClass());
		xs.alias("item", Articles.class);
		xml = xs.toXML(oms);
		
		}
		return xml;
	}
	
	//连接网络
	public static String getConnect(InMessage msg) {
		NewsOutMessage oms = new NewsOutMessage();
		try {
			setMsgInfo(oms,msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		XStream xs = XStreamFactory.init(true);
		String xml = "";
		List<Articles> arts = new ArrayList<Articles>();
		Articles art2 = new Articles();
		art2.setTitle("所有店铺");
		art2.setPicUrl("http://"+IPADDRESS+"/images/allshop.jpg"); //200*200
		art2.setDescription("点击此处可进入所有店铺列表");
		art2.setUrl("http://"+IPADDRESS+"/join.jsp");
		arts.add(art2);											
		((NewsOutMessage) oms).setArticles(arts);
		xs.alias("xml", oms.getClass());
		xs.alias("item", Articles.class);
		xml = xs.toXML(oms);
		return xml;		
	}	
	
	public static String toHexString(String s) {
        String str = "";  
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);  
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;//0x表示十六进制   "0x" + 
    }
	
	
}
